package cn.aitrox.ry.util;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class ObjectUtil {

    private static final String SERIS_FIELD_NAME = "serialVersionUID";

    public static boolean isEmpty(Object obj) {
        if (obj == null) {
            return true;
        }

        if (obj instanceof Optional) {
            return !((Optional) obj).isPresent();
        }
        if (obj instanceof CharSequence) {
            return ((CharSequence) obj).length() == 0;
        }
        if (obj.getClass().isArray()) {
            return Array.getLength(obj) == 0;
        }
        if (obj instanceof Collection) {
            return ((Collection) obj).isEmpty();
        }
        if (obj instanceof Map) {
            return ((Map) obj).isEmpty();
        }

        // else
        return false;
    }

    public static boolean notEmpty(Object obj) {
        return !isEmpty(obj);
    }

    public static Map<String, Object> obj2Map(Object obj) {

        Map<String, Object> map = new HashMap<>();

        Class clazz = obj.getClass();

        try {
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                String fieldName = field.getName();
                if (SERIS_FIELD_NAME.equals(fieldName)) {
                    continue;
                }
                map.put(fieldName, field.get(obj));
            }
        } catch (IllegalAccessException e) {
            return null;
        }
        return map;
    }

}
